<template>
  <view class="products">
    <view class="header">
      <text class="title">商品管理</text>
      <button class="btn-add" @click="showAddProduct = true">添加商品</button>
    </view>

    <view class="filters">
      <view class="filter-row">
        <input class="search-input" v-model="searchKeyword" placeholder="搜索商品名称或描述" @input="searchProducts" />
        <picker :value="categoryIndex" :range="categories" @change="onCategoryChange">
          <view class="filter-picker">{{ categories[categoryIndex] }}</view>
        </picker>
      </view>
      <view class="filter-row">
        <picker :value="statusIndex" :range="statusOptions" @change="onStatusChange">
          <view class="filter-picker">{{ statusOptions[statusIndex] }}</view>
        </picker>
        <picker :value="stockStatusIndex" :range="stockStatusOptions" @change="onStockStatusChange">
          <view class="filter-picker">{{ stockStatusOptions[stockStatusIndex] }}</view>
        </picker>
      </view>
    </view>

    <view class="product-list">
      <view v-for="product in products" :key="product.id" class="product-item">
        <view class="product-image">
          <image v-if="product.imageUrl" :src="product.imageUrl" class="product-img" />
          <text v-else class="no-image">无图片</text>
        </view>

        <view class="product-info">
          <text class="product-name">{{ product.name }}</text>
          <text class="product-desc">{{ product.description || '暂无描述' }}</text>
          <view class="product-details">
            <text class="product-price">价格: ¥{{ product.price }}</text>
            <text class="product-points">积分: {{ product.pointsPrice }}</text>
            <text class="product-stock">库存: {{ product.stock }}</text>
            <text class="product-category">分类: {{ product.category }}</text>
          </view>
        </view>

        <view class="product-status">
          <text class="status-badge" :class="[product.status === 1 ? 'status-active' : 'status-inactive']">
            {{ product.status === 1 ? '上架' : '下架' }}
          </text>
          <text class="stock-status"
            :class="[product.stock <= 0 ? 'stock-out' : product.stock <= 10 ? 'stock-low' : 'stock-normal']">
            {{ product.stock <= 0 ? '缺货' : product.stock <= 10 ? '低库存' : '正常' }} </text>
              <view class="product-tags">
                <text v-if="product.isHot" class="tag hot">热门</text>
                <text v-if="product.isNew" class="tag new">新品</text>
                <text v-if="product.isFeatured" class="tag featured">推荐</text>
              </view>
        </view>

        <view class="product-actions">
          <button class="btn-edit" @click="editProduct(product)">编辑</button>
          <button class="btn-stock" @click="adjustStock(product)">调库存</button>
          <button class="btn-toggle" :class="product.status === 1 ? 'btn-disable' : 'btn-enable'"
            @click="toggleProductStatus(product)">
            {{ product.status === 1 ? '下架' : '上架' }}
          </button>
          <button class="btn-delete" @click="deleteProduct(product.id)">删除</button>
        </view>
      </view>
    </view>

    <view class="pagination">
      <button class="page-btn" :disabled="currentPage <= 1" @click="loadProducts(currentPage - 1)">
        上一页
      </button>
      <text class="page-info">{{ currentPage }} / {{ totalPages }}</text>
      <button class="page-btn" :disabled="currentPage >= totalPages" @click="loadProducts(currentPage + 1)">
        下一页
      </button>
    </view>

    <!-- 添加/编辑商品弹窗 -->
    <view v-if="showAddProduct || editingProduct" class="modal-overlay" @click="closeProductModal">
      <view class="modal" @click.stop>
        <view class="modal-header">
          <text class="modal-title">{{ editingProduct ? '编辑商品' : '添加商品' }}</text>
          <text class="modal-close" @click="closeProductModal">×</text>
        </view>
        <view class="modal-body">
          <view class="form-group">
            <text class="form-label">商品名称</text>
            <input class="form-input" v-model="productForm.name" placeholder="请输入商品名称" />
          </view>
          <view class="form-group">
            <text class="form-label">商品描述</text>
            <textarea class="form-textarea" v-model="productForm.description" placeholder="请输入商品描述"></textarea>
          </view>
          <view class="form-group">
            <text class="form-label">价格</text>
            <input class="form-input" type="number" v-model="productForm.price" placeholder="请输入价格" />
          </view>
          <view class="form-group">
            <text class="form-label">积分价格</text>
            <input class="form-input" type="number" v-model="productForm.pointsPrice" placeholder="请输入积分价格" />
          </view>
          <view class="form-group">
            <text class="form-label">库存</text>
            <input class="form-input" type="number" v-model="productForm.stock" placeholder="请输入库存数量" />
          </view>
          <view class="form-group">
            <text class="form-label">分类</text>
            <input class="form-input" v-model="productForm.category" placeholder="请输入商品分类" />
          </view>
          <view class="form-group">
            <text class="form-label">图片URL</text>
            <input class="form-input" v-model="productForm.imageUrl" placeholder="请输入图片URL" />
          </view>
          <view class="form-group">
            <text class="form-label">商品标签</text>
            <view class="checkbox-group">
              <label class="checkbox-item">
                <checkbox :checked="productForm.isHot" @change="toggleTag('isHot')" />
                <text>热门商品</text>
              </label>
              <label class="checkbox-item">
                <checkbox :checked="productForm.isNew" @change="toggleTag('isNew')" />
                <text>新品</text>
              </label>
              <label class="checkbox-item">
                <checkbox :checked="productForm.isFeatured" @change="toggleTag('isFeatured')" />
                <text>推荐商品</text>
              </label>
            </view>
          </view>
        </view>
        <view class="modal-footer">
          <button class="btn-cancel" @click="closeProductModal">取消</button>
          <button class="btn-confirm" @click="saveProduct">保存</button>
        </view>
      </view>
    </view>

    <!-- 调整库存弹窗 -->
    <view v-if="showStockModal" class="modal-overlay" @click="closeStockModal">
      <view class="modal" @click.stop>
        <view class="modal-header">
          <text class="modal-title">调整库存</text>
          <text class="modal-close" @click="closeStockModal">×</text>
        </view>
        <view class="modal-body">
          <view class="stock-info">
            <text class="current-stock">当前库存: {{ stockProduct ? stockProduct.stock : 0 }}</text>
          </view>
          <view class="form-group">
            <text class="form-label">调整数量</text>
            <input class="form-input" type="number" v-model="stockForm.adjustment" placeholder="正数为增加，负数为减少" />
          </view>
          <view class="form-group">
            <text class="form-label">调整原因</text>
            <textarea class="form-textarea" v-model="stockForm.reason" placeholder="请输入调整原因"></textarea>
          </view>
        </view>
        <view class="modal-footer">
          <button class="btn-cancel" @click="closeStockModal">取消</button>
          <button class="btn-confirm" @click="saveStockAdjustment">确认调整</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      products: [],
      searchKeyword: '',
      currentPage: 1,
      totalPages: 1,
      pageSize: 10,

      // 筛选条件
      categories: ['全部分类', '打印服务', '办公用品', '数码产品', '其他'],
      categoryIndex: 0,
      statusOptions: ['全部状态', '上架', '下架'],
      statusIndex: 0,
      stockStatusOptions: ['全部库存', '正常', '低库存', '缺货'],
      stockStatusIndex: 0,

      // 添加/编辑商品
      showAddProduct: false,
      editingProduct: null,
      productForm: {
        name: '',
        description: '',
        price: 0,
        pointsPrice: 0,
        stock: 0,
        category: '',
        imageUrl: '',
        isHot: false,
        isNew: false,
        isFeatured: false
      },

      // 调整库存
      showStockModal: false,
      stockProduct: null,
      stockForm: {
        adjustment: 0,
        reason: ''
      }
    }
  },

  onLoad() {
    this.loadProducts()
  },

  methods: {
    async loadProducts(page = 1) {
      try {
        const token = uni.getStorageSync('token')
        if (!token) {
          uni.navigateTo({ url: '/pages/auth/login' })
          return
        }

        const params = new URLSearchParams({
          page: page.toString(),
          limit: this.pageSize.toString(),
          search: this.searchKeyword
        })

        if (this.categoryIndex > 0) {
          params.append('category', this.categories[this.categoryIndex])
        }

        if (this.statusIndex > 0) {
          params.append('status', this.statusIndex.toString())
        }

        if (this.stockStatusIndex > 0) {
          const stockStatusMap = { 1: 'normal', 2: 'low', 3: 'out' }
          params.append('stockStatus', stockStatusMap[this.stockStatusIndex])
        }

        const res = await uni.request({
          url: `https://ydy.lg1012.cn/api/admin/products?${params.toString()}`,
          method: 'GET',
          header: {
            'Authorization': `Bearer ${token}`
          }
        })

        if (res.data.success) {
          this.products = res.data.data.products || []
          this.currentPage = res.data.data.currentPage || 1
          this.totalPages = res.data.data.totalPages || 1
        }
      } catch (error) {
        console.error('加载商品失败:', error)
        uni.showToast({
          title: '加载商品失败',
          icon: 'none'
        })
      }
    },

    searchProducts() {
      clearTimeout(this.searchTimer)
      this.searchTimer = setTimeout(() => {
        this.loadProducts(1)
      }, 500)
    },

    onCategoryChange(e) {
      this.categoryIndex = e.detail.value
      this.loadProducts(1)
    },

    onStatusChange(e) {
      this.statusIndex = e.detail.value
      this.loadProducts(1)
    },

    onStockStatusChange(e) {
      this.stockStatusIndex = e.detail.value
      this.loadProducts(1)
    },

    editProduct(product) {
      this.editingProduct = product
      this.productForm = {
        name: product.name || '',
        description: product.description || '',
        price: product.price || 0,
        pointsPrice: product.pointsPrice || 0,
        stock: product.stock || 0,
        category: product.category || '',
        imageUrl: product.imageUrl || '',
        isHot: product.isHot || false,
        isNew: product.isNew || false,
        isFeatured: product.isFeatured || false
      }
    },

    async toggleProductStatus(product) {
      const action = product.status === 1 ? '下架' : '上架'
      uni.showModal({
        title: `确认${action}`,
        content: `确定要${action}商品 ${product.name} 吗？`,
        success: async (res) => {
          if (res.confirm) {
            try {
              const token = uni.getStorageSync('token')
              const updateRes = await uni.request({
                url: `https://ydy.lg1012.cn/api/admin/products/${product.id}`,
                method: 'PUT',
                header: {
                  'Authorization': `Bearer ${token}`,
                  'Content-Type': 'application/json'
                },
                data: {
                  status: product.status === 1 ? 0 : 1
                }
              })

              if (updateRes.data.success) {
                uni.showToast({ title: `${action}成功` })
                this.loadProducts(this.currentPage)
              }
            } catch (error) {
              uni.showToast({ title: `${action}失败`, icon: 'none' })
            }
          }
        }
      })
    },

    async deleteProduct(productId) {
      uni.showModal({
        title: '确认删除',
        content: '确定要删除这个商品吗？删除后无法恢复。',
        success: async (res) => {
          if (res.confirm) {
            try {
              const token = uni.getStorageSync('token')
              const deleteRes = await uni.request({
                url: `https://ydy.lg1012.cn/api/admin/products/${productId}`,
                method: 'DELETE',
                header: {
                  'Authorization': `Bearer ${token}`
                }
              })

              if (deleteRes.data.success) {
                uni.showToast({ title: '删除成功' })
                this.loadProducts(this.currentPage)
              }
            } catch (error) {
              uni.showToast({ title: '删除失败', icon: 'none' })
            }
          }
        }
      })
    },

    adjustStock(product) {
      this.stockProduct = product
      this.showStockModal = true
      this.stockForm = {
        adjustment: 0,
        reason: ''
      }
    },

    async saveStockAdjustment() {
      if (!this.stockForm.adjustment || this.stockForm.adjustment === 0) {
        uni.showToast({ title: '请输入调整数量', icon: 'none' })
        return
      }

      if (!this.stockForm.reason) {
        uni.showToast({ title: '请输入调整原因', icon: 'none' })
        return
      }

      try {
        const token = uni.getStorageSync('token')
        const res = await uni.request({
          url: `https://ydy.lg1012.cn/api/admin/products/${this.stockProduct.id}/stock`,
          method: 'POST',
          header: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          },
          data: this.stockForm
        })

        if (res.data.success) {
          uni.showToast({ title: '库存调整成功' })
          this.closeStockModal()
          this.loadProducts(this.currentPage)
        }
      } catch (error) {
        uni.showToast({ title: '库存调整失败', icon: 'none' })
      }
    },

    closeProductModal() {
      this.showAddProduct = false
      this.editingProduct = null
      this.productForm = {
        name: '',
        description: '',
        price: 0,
        pointsPrice: 0,
        stock: 0,
        category: '',
        imageUrl: '',
        isHot: false,
        isNew: false,
        isFeatured: false
      }
    },

    closeStockModal() {
      this.showStockModal = false
      this.stockProduct = null
      this.stockForm = {
        adjustment: 0,
        reason: ''
      }
    },

    async saveProduct() {
      if (!this.productForm.name) {
        uni.showToast({ title: '请输入商品名称', icon: 'none' })
        return
      }

      if (!this.productForm.price || this.productForm.price <= 0) {
        uni.showToast({ title: '请输入有效价格', icon: 'none' })
        return
      }

      try {
        const token = uni.getStorageSync('token')
        const url = this.editingProduct
          ? `https://ydy.lg1012.cn/api/admin/products/${this.editingProduct.id}`
          : 'https://ydy.lg1012.cn/api/admin/products'

        const res = await uni.request({
          url,
          method: this.editingProduct ? 'PUT' : 'POST',
          header: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          },
          data: this.productForm
        })

        if (res.data.success) {
          uni.showToast({ title: '保存成功' })
          this.closeProductModal()
          this.loadProducts(this.currentPage)
        }
      } catch (error) {
        uni.showToast({ title: '保存失败', icon: 'none' })
      }
    },

    toggleTag(tagName) {
      this.productForm[tagName] = !this.productForm[tagName]
    }
  }
}
</script>

<style scoped>
.products {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.btn-add {
  background-color: #007bff;
  color: white;
  border: none;
  padding: 16rpx 32rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.filters {
  background: white;
  padding: 20rpx;
  border-radius: 12rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.filter-row {
  display: flex;
  gap: 20rpx;
  margin-bottom: 20rpx;
}

.filter-row:last-child {
  margin-bottom: 0;
}

.search-input {
  flex: 1;
  padding: 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.filter-picker {
  padding: 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
  background-color: #f8f9fa;
  min-width: 200rpx;
  text-align: center;
}

.product-list {
  background: white;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  margin-bottom: 30rpx;
}

.product-item {
  display: flex;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;
}

.product-item:last-child {
  border-bottom: none;
}

.product-image {
  width: 120rpx;
  height: 120rpx;
  margin-right: 20rpx;
  border-radius: 8rpx;
  overflow: hidden;
  background-color: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
}

.product-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.no-image {
  font-size: 24rpx;
  color: #999;
}

.product-info {
  flex: 1;
  margin-right: 20rpx;
}

.product-name {
  display: block;
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 8rpx;
}

.product-desc {
  display: block;
  font-size: 24rpx;
  color: #666;
  margin-bottom: 12rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.product-details {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 8rpx;
}

.product-price,
.product-points,
.product-stock,
.product-category {
  font-size: 24rpx;
  color: #999;
}

.product-status {
  margin-right: 20rpx;
  text-align: center;
}

.status-badge {
  display: block;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  color: white;
  margin-bottom: 8rpx;
}

.status-active {
  background-color: #28a745;
}

.status-inactive {
  background-color: #dc3545;
}

.stock-status {
  display: block;
  font-size: 20rpx;
  padding: 4rpx 8rpx;
  border-radius: 4rpx;
  margin-bottom: 8rpx;
}

.stock-normal {
  background-color: #d4edda;
  color: #155724;
}

.stock-low {
  background-color: #fff3cd;
  color: #856404;
}

.stock-out {
  background-color: #f8d7da;
  color: #721c24;
}

.product-tags {
  display: flex;
  gap: 4rpx;
  flex-wrap: wrap;
}

.tag {
  font-size: 18rpx;
  padding: 2rpx 8rpx;
  border-radius: 4rpx;
  color: white;
}

.tag.hot {
  background-color: #ff4757;
}

.tag.new {
  background-color: #2ed573;
}

.tag.featured {
  background-color: #ffa502;
}

.product-actions {
  display: flex;
  flex-direction: column;
  gap: 12rpx;
}

.btn-edit,
.btn-stock,
.btn-toggle,
.btn-delete {
  border: none;
  padding: 12rpx 24rpx;
  border-radius: 6rpx;
  font-size: 24rpx;
  color: white;
}

.btn-edit {
  background-color: #007bff;
}

.btn-stock {
  background-color: #17a2b8;
}

.btn-enable {
  background-color: #28a745;
}

.btn-disable {
  background-color: #dc3545;
}

.btn-delete {
  background-color: #6c757d;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 30rpx;
  padding: 30rpx;
}

.page-btn {
  background-color: #007bff;
  color: white;
  border: none;
  padding: 16rpx 32rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.page-btn:disabled {
  background-color: #ccc;
}

.page-info {
  font-size: 28rpx;
  color: #666;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal {
  background: white;
  border-radius: 12rpx;
  width: 90%;
  max-width: 600rpx;
  max-height: 80vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;
}

.modal-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.modal-close {
  font-size: 48rpx;
  color: #999;
}

.modal-body {
  padding: 30rpx;
}

.form-group {
  margin-bottom: 30rpx;
}

.form-label {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 12rpx;
}

.form-input,
.form-textarea {
  width: 100%;
  padding: 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
  box-sizing: border-box;
}

.form-textarea {
  height: 120rpx;
  resize: vertical;
}

.checkbox-group {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.checkbox-item {
  display: flex;
  align-items: center;
  gap: 12rpx;
}

.stock-info {
  background-color: #f8f9fa;
  padding: 20rpx;
  border-radius: 8rpx;
  margin-bottom: 20rpx;
}

.current-stock {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 20rpx;
  padding: 30rpx;
  border-top: 1rpx solid #eee;
}

.btn-cancel {
  background-color: #6c757d;
  color: white;
  border: none;
  padding: 16rpx 32rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.btn-confirm {
  background-color: #007bff;
  color: white;
  border: none;
  padding: 16rpx 32rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
}
</style>